﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;
using System.Data.SQLite;
using System.Security.Cryptography.X509Certificates;
using System.Data.Common;
using System.Net.WebSockets;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Net;

namespace SocketClient
{
    public partial class MainForm : Form
    {
        private LoginForm loginForm;
        private ConnServer conn;
        private string domain;
        private SqlLiteUtils sqlLite;
        private String webSocketLinkUrl = "";

        public MainForm()
        {
            InitializeComponent();
            InitDomainConfig();
            getUserInfo();
            this.txtWS.Text = GValues.domainLink.Replace("http","ws").Replace("https","wss") + "websocket/" + GValues.tenant + "-" + GValues.account + "-print" ;
            webSocketLinkUrl = GValues.domainLink.Replace("http", "ws").Replace("https", "wss") + "websocket/" + GValues.tenant + "-" + GValues.account + "-print";
        }

        private void LoginForm_TransferValue(string value) {
            this.txtWS.Text = value;

        }
        private void LoginForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            // 当窗口关闭时，将 loginForm 设置为 null
            loginForm = null;
            sqlLite = null;
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            this.cboType.SelectedIndex = 0;
            BtnConn_Click(null ,null);
        }

        private void Thread_conn(object obj)
        {
            string[] array = (string[])obj;
            this.conn = new ConnServer(array[0], int.Parse(array[1]), array[2]);
            this.conn.Connect();
        }


        private void BtnConn_Click(object sender, EventArgs e)
        {
            if (!(this.btnConn.Text == "连接"))
            {
                if (this.btnConn.Text == "断开")
                {
                    this.conn.CloseConnect();
                    this.btnConn.Text = "连接";
                }
                return;
            }
            this.btnConn.Enabled = false;
            this.btnConn.Text = "连接中.";
            Thread thread = new Thread(new ParameterizedThreadStart(this.Thread_conn));
            thread.IsBackground = true;
            if (this.cboType.SelectedIndex == 1)
            {
                thread.Start(new string[]
                {
                    this.txtIP.Text,
                    this.txtPort.Text,
                    this.cboType.Text
                });
                return;
            }
            thread.Start(new string[]
            {
                webSocketLinkUrl,
                "0",
                this.cboType.Text
            });
        }

        private void BtnSend_Click(object sender, EventArgs e)
        {
            this.conn.SSend(this.txtMsg.Text.Trim());
        }

        private void CboType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cboType.SelectedIndex == 0)
            {
                this.panel.Visible = false;
            }
            else
            {
                this.panel.Visible = true;
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
            //Environment.Exit(0);
        }

        public void AddLog(string text)
        {
            if (this.rtxtMsg.InvokeRequired)
            {
                this.rtxtMsg.Invoke(new Action<string>(AddLog), text);
            }
            else
            {
                this.rtxtMsg.AppendText(text + Environment.NewLine);
                this.rtxtMsg.SelectionStart = this.rtxtMsg.TextLength;
                this.rtxtMsg.ScrollToCaret();
            }
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            string text = null;
            ConnServer.que_msg.TryDequeue(out text);
            if (text != null)
            {
                if (!text.Contains("@heart"))
                {
                    AddLog(text);
                }
                if (text.Contains("连接成功！"))
                {
                    this.btnConn.Enabled = true;
                    this.btnConn.Text = "断开";
                    this.btnSend.Enabled = true;
                    return;
                }
                if (text.Contains("连接失败！") || text.Contains("连接断开！"))
                {
                    this.btnConn.Enabled = true;
                    this.btnConn.Text = "连接";
                    this.btnSend.Enabled = false;
                }
            }
        }

        private void txtIP_TextChanged(object sender, EventArgs e)
        {

        }

        private void rtxtMsg_TextChanged(object sender, EventArgs e)
        {

        }

        #region 操作函数代码块
        public void InitDomainConfig()
        {
            // 指定配置文件的路径
            string configFilePath = GValues.configPath; //"E:\\Program Files\\Autodesk\\AutoCAD 2014\\erptestdll\\config.txt";
            try
            {
                // 读取文本文件的所有行
                string[] lines = File.ReadAllLines(configFilePath);

                // 遍历每一行并处理配置信息
                foreach (string line in lines)
                {
                    // 假设配置文件的每一行都是以"键=值"的格式存储
                    string[] keyValue = line.Split('=');
                    if (keyValue.Length == 2)
                    {
                        string key = keyValue[0].Trim();
                        string value = keyValue[1].Trim();
                        // 在这里处理配置信息，例如存储到字典或使用
                        if (key == "domain")
                        {
                            domain = value;
                            GValues.domain = value;
                        }
                        try
                        {
                            if (key == "domainLink")
                            {
                                GValues.domainLink = value;
                            }
                            if (key == "searchPath")
                            {
                                GValues.searchPath = value;
                            }
                        }
                        catch (System.Exception e)
                        {
                            LogHelper.WriteLog(e.ToString(),null);
                        }
                    }
                }
            }
            catch (IOException e)
            {
                LogHelper.WriteLog("读取配置文件时发生错误: " + e.Message,null);
            }

        }

        private void getUserInfo()
        {
            //sqlLite = new SqlLiteUtils();
            //sqlLite.createDb();
            try
            {
                sqlLite = new SqlLiteUtils();
                //sqlLite.createDb();
                //String password = StringSecurity.DESEncrypt("123456");
                //sqlLite.insertData("admin", password);
                //String encode = StringSecurity.DESDecrypt(password);
                string sql = "select account,password,domainid,token from user";
                SQLiteDBHelper db = new SQLiteDBHelper(GValues.dbpath);
                using (SQLiteDataReader reader = db.ExecuteReader(sql, null))
                {
                    while (reader.Read())
                    {
                        //editor.WriteMessage(reader.GetString(0) + " " + reader.GetString(1) + "\n");
                        //Console.WriteLine("account:{0},password{1}", reader.GetString(0), reader.GetString(1));
                        GValues.account = reader.GetString(0);
                        GValues.password = StringSecurity.DESDecrypt(reader.GetString(1));
                        GValues.tenant = reader.GetString(2);
                        GValues.token = reader.GetString(3);
                    }
                }
            }
            catch (System.Exception e)
            {
                LogHelper.WriteLog(e.ToString(),null);
            }
        }
        private void GetDomainTenant()
        {
            Http.CreateHttpClient().GetAsync(GValues.domainLink + "saas/data/get?domain=" + domain, new Action<Http.HttpResp>((r) =>
            {
                var responCode = Convert.ToInt32(r.Code);
                if (responCode == 200) //访问成功
                {
                    GValues.tenant = r.AckStr();
                    loginForm.domainid = r.AckStr().ToString();
                    loginForm.enablelogin = true;
                    //editor.WriteMessage("Domain: " + r.AckStr().ToString());
                }
                else
                {
                    LogHelper.WriteLog(r.Code + " " + " " + responCode + " " + r.Error,null);
                }
            }));
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            if (loginForm == null)
            {
                // 创建 Windows Form 窗口
                loginForm = new LoginForm();
                loginForm.FormClosed += LoginForm_FormClosed;
                // 订阅事件
                loginForm.TransferValue += LoginForm_TransferValue;
                loginForm.Show();
                
            }
            InitDomainConfig();
            GetDomainTenant();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            PrintPdf print = new PrintPdf();
            String wo = "W-20240429-0001";
            wo = this.textBox1.Text.ToUpper().Trim();
            print.orderprint(wo);
        }

        private void txtMsg_TextChanged(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            Print print = new Print();
            print.orderprint("W-20240429-021");
        }

    }
}
